package com.yunxi.common.config;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.yunxi.controller.customer.CustomCreditReportingController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class OSSUtil {

 /*   public static final String KEY="LTAIqX1zgsl6NRso";
    public static final String PASS="QM8sJXxjWIGmmKEGnaDR21n5LBmXFJ";
    public static final String ENDPOINT="http://oss-cn-shanghai.aliyuncs.com";
    public static final String BucketName="aiways-pms-pre";
    public static final String ENDPOINT_DOMAIN="oss-cn-shanghai.aliyuncs.com";*/
    @Value("${OSS.KEY}")
    public String KEY;
    @Value("${OSS.PASS}")
    public String PASS;
    @Value("${OSS.ENDPOINT}")
    public String ENDPOINT;
    @Value("${OSS.BUCKET.NAME}")
    public String BucketName;
    @Value("${OSS.ENDPOINT.DOMAIN}")
    public String ENDPOINT_DOMAIN;
    @Value("${OSS.READ}")
    public String READ="false";

    @Value("${spring.profiles.active}")
    public String ENV;

    //public static final String KEY="LTAIPHchUUgvn6Ja";
    //public static final String PASS="a86Pu7zTxl1P0dmCqK2Q5lv5d2kajI";
    //public static final String ENDPOINT="http://oss-cn-shenzhen.aliyuncs.com";
    //public static final String BucketName="tcb-erp-image";
    //public static final String ENDPOINT_DOMAIN="oss-cn-shenzhen.aliyuncs.com";

  /*  public static void uploadFile(String object_name,File file) throws FileNotFoundException {
        String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
        //String accessKeyId = "LTAIPHchUUgvn6Ja";
        //String accessKeySecret = "a86Pu7zTxl1P0dmCqK2Q5lv5d2kajI";
        //String bucketName = "tcb-erp-image";
        String accessKeyId = "LTAIqX1zgsl6NRso";
        String accessKeySecret = "QM8sJXxjWIGmmKEGnaDR21n5LBmXFJ";
        String bucketName = "aiways-pms-pre";
// 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        InputStream inputStream = new FileInputStream(file);
        ossClient.putObject(bucketName, object_name, inputStream);
// 关闭OSSClient。
        ossClient.shutdown();
    }
*/
    public void uploadFile(String object_name, MultipartFile file) throws IOException {
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
// 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(ENDPOINT, KEY, PASS);
// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        ossClient.putObject(BucketName, object_name, file.getInputStream());
// 关闭OSSClient。
        ossClient.shutdown();
    }

   public void download2(List<String> urlList,String savePath) throws Exception {
      for (String url : urlList) {
         download(url,url.substring(url.lastIndexOf("/")+1),savePath);
      }
   }


   public void download(String urlString, String filename,String savePath) throws Exception {
      // 构造URL
      URL url = new URL(urlString);
      // 打开连接
      URLConnection con = url.openConnection();
      //设置请求超时为5s
      con.setConnectTimeout(5*1000);
      // 输入流
      InputStream is = con.getInputStream();

      // 1K的数据缓冲
      byte[] bs = new byte[1024];
      // 读取到的数据长度
      int len;
      // 输出的文件流
      File file=new File(savePath);
      if(!file.exists()){
         file.mkdirs();
      }
      // 获取图片的扩展名
      String extensionName = filename.substring(filename.lastIndexOf(".") +     1);
      // 新的图片文件名 = 编号 +"."图片扩展名
      String newFileName = "aaaaaaa"+ "." + extensionName;
      OutputStream os = new FileOutputStream(file.getPath()+"\\"+filename);
      // 开始读取
      while ((len = is.read(bs)) != -1) {
         os.write(bs, 0, len);
      }
      // 完毕，关闭所有链接
      os.close();
      is.close();
   }

   public static void main(String arsg[]) throws Exception {
        //OSSClient client = new OSSClient(OSSUtil.ENDPOINT, OSSUtil.KEY, OSSUtil.PASS);
        //long expireTime = 3600;//64800
        //long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        //Date expiration = new Date(expireEndTime);
        //String aaa = client.generatePresignedUrl(OSSUtil.BucketName,"uploadFiles/123123/20190610174724bb2655e63914410ad75e6GafBD.png",expiration).toString();
        //System.out.println(aaa);
//        String aaa = "http://oss-cn-shanghai.aliyuncs.com/12312312321";
//        System.out.println(aaa.substring(aaa.indexOf("aliyuncs.com")+13));


//       ArrayList<String> list = new ArrayList<>();
//       list.add("uploadFiles/AAAA/201909221958348f31b277517e4b9f6Y7S88EYF6.jpg");
//       String bucketName = "pms-image";
//       String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
//       String key = "LTAITlzonnDhUhVH";
//       String pass = "zp4lWIad7cGOHKipLKcqG4iTSZGLOP";

//       downloadOSS(bucketName,list,endpoint,key,pass);

//       String u = "https://aiways-aichizhixingapp.oss-cn-shanghai.aliyuncs.com/dev/vedio/8bf93210-5813-41ff-8fec-e18db317b995.jpg";
//       String fileName = u.substring(u.lastIndexOf("/") +     1);
//       System.out.println(fileName);
//       download(u,fileName,"C:\\Users\\Lzk\\Desktop");

//       String s = "http://pms-image.oss-cn-shenzhen.aliyuncs.com/prod/avatar/2217b2aa-890f-4d1e-92b1-6319380f3dbd.png?Expires=1571061990&OSSAccessKeyId=http%3A%2F%2Foss-cn-shenzhen.aliyuncs.com&Signature=Ku609zoO%2FUWyGymdJ4T%2Bo1s4Rn4%3D";
//       s=s.substring(0,s.indexOf("?"));
//       System.out.println(s);
//       System.out.println("---");
//       System.out.println(s.substring(s.lastIndexOf(".com") + 5));
    }

    public String downloadUrl(String sourceUrl) throws IOException {
        OSSClient client = new OSSClient(ENDPOINT, KEY, PASS);
        long expireTime = 3600;//64800
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        //key转换
        if(sourceUrl.startsWith("http")){
            sourceUrl = sourceUrl.substring(sourceUrl.indexOf("aliyuncs.com")+13);
        }
        return client.generatePresignedUrl(BucketName,sourceUrl,expiration).toString();
    }


   /**
    * 从OSS服务中下载所需文件到本地临时文件
    * @param
    * @param objectNames 要下载的对象/文件
    * @return
    */
   public String downloadOSS(List<String> attachUrlList, List<String> objectNames,String filePath) throws UnsupportedEncodingException {
      OSSClient ossClient = null;
      try{
         ossClient = new OSSClient(ENDPOINT, KEY, PASS);
         //创建OSSClient实例，用于操作oss空间
         if ("prod".equals(ENV)){
            objectNames.clear();
            for (String key : attachUrlList) {
               long expireTime = 3600;//64800
               long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
               Date expiration = new Date(expireEndTime);
               //key转换
               if(key.startsWith("http")){
                  key = key.substring(key.indexOf("aliyuncs.com")+13);
               }
               String realUrl = ossClient.generatePresignedUrl(BucketName, key, expiration).toString();
               realUrl = realUrl.substring(0,realUrl.indexOf("?"));
               realUrl = realUrl.substring(realUrl.lastIndexOf(".com") + 5);
               objectNames.add(realUrl);
               System.out.println(realUrl);
            }
         }
         //判断文件目录是否存在，不存在则创建
         File file = new File(filePath);
         if (!file.exists()){
            file.mkdirs();
         }
         for (String objectName:objectNames){
            //判断保存文件名是否加后缀
//            if (objectName.contains(".")){
               //指定文件保存名称
               String fullPath = filePath+"/"+System.currentTimeMillis()+objectName.substring(objectName.lastIndexOf("/")+1);
//            }
            System.out.println("文件全路径"+fullPath);
            //获取OSS文件并保存到本地指定路径中，此文件路径一定要存在，若保存目录不存在则报错，若保存文件名已存在则覆盖本地文件
            ossClient.getObject(new GetObjectRequest(BucketName,objectName),new File(fullPath));
         }
      }catch (Exception e){
         System.out.println(e.getMessage());
         e.printStackTrace();
         throw new RuntimeException(e.getMessage());
      }finally {
         //关闭oss连接
         if (ossClient != null){
            ossClient.shutdown();
         }
      }
      return filePath;
   }

}
